<%@page import="com.shuohe.entity.system.user.User"%>
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<%@ page language="java" import="java.util.*"%>
<%@ page import="com.shuohe.util.json.*" %>
<%@page import="java.io.PrintWriter"%>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path;
    String formName = request.getParameter("formName");
    User user = null;
    String userJson = null;
    String permissionssJson = null;
    PrintWriter ss = response.getWriter();
    try
    {
        user = (User)session.getAttribute("user");
        if(user==null)
        {
          System.out.println("user = null");
          //response.sendRedirect(basePath+"/pages/login.jsp");
          String topLocation = "<script>top.location.href=\""+basePath+"/pages/login.jsp\"</script>";
          ss.print(topLocation);
        }
        else
        {
            userJson = Json.toJsonByPretty(user);
        }
    }
    catch(Exception e)
    {
        String topLocation = "<script>top.location.href=\""+basePath+"/pages/login.jsp\"</script>";
        ss.print(topLocation);
        e.printStackTrace();
    }
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>表单数据管理</title>
<link type="text/css" href="<%=basePath%>/TopJUI/topjui/css/topjui.core.min.css" rel="stylesheet">
<link type="text/css" href="<%=basePath%>/TopJUI/topjui/themes/default/topjui.green.css" rel="stylesheet" id="dynamicTheme"/>
<link type="text/css" href="<%=basePath%>/TopJUI/topjui/plugins/font-awesome/css/font-awesome.min.css" rel="stylesheet"/>
<link type="text/css" href="<%=basePath%>/pages/css/add-form.css" rel="stylesheet" />
</head>
<body>
<div class="easyui-panel" data-options="fit:true">
  <div id="formTableLeft" class="form-order-table-con">

  </div>
  <div id="formTableRight" class="form-order-table-con">
    <table id="dg" style="width:100%;height:100%;">

  	</table>
  	<div id="tb" style="padding:0px 30px;height: 35px">
      <a href="#" class="easyui-linkbutton" btnCls="topjui-btn-normal" plain="true" iconCls="fa fa-plus" onclick="functionAdd()">新增</a>
      <a href="#" class="easyui-linkbutton" btnCls="topjui-btn-normal" plain="true" iconCls="fa fa-pencil" onclick="functionModify()">修改</a>
      <a href="#" class="easyui-linkbutton" btnCls="topjui-btn-normal" plain="true" iconCls="fa fa-info-circle" onclick="functionView()">查看</a>
      <a href="#" class="easyui-linkbutton" btnCls="topjui-btn-normal" plain="true" iconCls="fa fa-trash" onclick="functionDelete()">删除</a>
      <!--<a href="#" class="easyui-linkbutton" btnCls="topjui-btn-normal" plain="true" iconCls="fa fa-line-chart" onclick="setCharts()">生成图表</a>-->
    </div>
  </div>
</div>
</body>
</html>
<script type="text/javascript" src="<%=basePath%>/TopJUI/topjui/plugins/jquery/jquery.min.js"></script>
<script type="text/javascript" src="<%=basePath%>/TopJUI/topjui/plugins/jquery/jquery.cookie.js"></script>
<script type="text/javascript" src="<%=basePath%>/TopJUI/static/public/js/topjui.config.js"></script>
<script type="text/javascript" src="<%=basePath%>/TopJUI/topjui/js/topjui.core.min.js"></script>
<script type="text/javascript" src="<%=basePath%>/TopJUI/topjui/js/locale/topjui.lang.zh_CN.js"></script>
<script type="text/javascript" src="<%=basePath%>/pages/js/moment.min.js"></script>
<script type="text/javascript" src="<%=basePath%>/pages/js/layer/layer.js"></script>
<script type="text/javascript" src="<%=basePath%>/pages/js/util.js"></script>
<script type="text/javascript" src="<%=basePath%>/pages/js/add-form.js"></script>
<script type="text/javascript" src="<%=basePath%>/js/common.js"></script>
<script type="text/javascript">
var fields = []
var columns = []
var result
var formName = '<%=formName%>'
var basePath = '<%=basePath%>'
var normalSelectData = new Object()
var key = '';
var formUrl = '';
var tableName = '';
var user = <%=userJson%>
var formFramework
var isAct
var dataUrl = ''
$(document).ready(function(){
	$.ajax({
	    url: "<%=basePath%>/profFormRel/getInfo",
	    type: "POST",
	    dataType:'json',
	    data:
	    {
	      'tableName': formName
	    },
	    error: function() //失败
	    {
	      messageloadError()
	    },
	    success: function(result)//成功
	    {
	      key = result.obj.proDefKey;
	      formUrl = result.obj.formUrl;
	      tableName = result.obj.formTableName;
	      //console.info(key+formUrl+tableName);
	    }
	  })
});
$(function(){
  // 初始化数据
  init (formName)
})
function init (title) {
  $.ajax({
    url: "<%=basePath%>/pages/crminterface/getDatagridForJson.do",
    type: "POST",
    dataType:'json',
    data:
    {
      'tableName': title
    },
    error: function() //失败
    {
      messageloadError()
    },
    success: function(data)//成功
    {
      result = data
      fields = result.field
      initTableCon(result)
      initNormalSelectData(result.field)
      $.ajax({
        url: "${pageContext.request.contextPath}/pages/button/framework/get.do",
        type: "POST",
        dataType:'json',
        data:
        {
          'title': title
        },
        error: function() //失败
        {
          messageloadError()
        },
        success: function(data)//成功
        {
          console.log(data)
          if (data.obj != null) {
        	  console.log(data.obj)
            formFramework = data.obj
            columns.push(initTableColumns(formFramework.columns))
            initTableButtons(formFramework.buttons)
            initTableSearch(formFramework, result)
            initTableJs(formFramework.js_code)
          } else {
            $.ajax({
              url: "<%=basePath%>/profFormRel/isAct",
              type: "POST",
              dataType:'text',
              async: false,
              data:
              {
                'tableName': formName
              },
              error: function() //失败
              {
                messageloadError()
              },
              success: function(data)//成功
              {
                data = $.trim(data)
                isAct = data
                if (data == '0') {
                  columns = initColumns(result.field, true)
                } else {
                  columns = initColumns(result.field, false)
                }
              }
            })
          }
          initTable(title)
        }
      })
    }
  })
}
function viewProcessDetail(uuid){
	layer.open({
	    type: 2,
	    title: '查看流程详细',
	    shadeClose: false,
	    shade: 0.3,
	    maxmin: true, //开启最大化最小化按钮
	    area: ['900px', document.body.clientHeight-20+'px'],
	    btn: '关闭',
	    content: 'processDetail.jsp?uuid=' + uuid,
	    //content: 'mtLogOrder.jsp',
	    yes:function(index){
	      layer.close(index)
	    }
	  })
	
}
function initTable (title) {
  if (result.needTree!='true') {
    $('#dg').datagrid({
      url: "<%=basePath%>/crm/ActionFormUtil/getByTableNameAndUserId.do?tableName="+title+"&create_user_id="+user.id,
      columns:columns,
      rownumbers:true,
      singleSelect:true,
      autoRowHeight:false,
      pagination:true,
      fitColumns:true,
      striped:true,
      toolbar:'#tb',
      pageSize:20
    })
  } else {
    
  }
  
}
//新增一条数据
function functionAdd () {
  var relate_id = ''
  if (result.needTree=='true') {
    var treeRow = $('#dg_tree').treegrid('getSelected')
    if (treeRow == null) {
      alert('请先选择一条数据')
      return false
    } else {
      relate_id = treeRow.id
    }
  }
  if (isAct == '0') {
    layer.open({
	    type: 2,
	    title: "添加数据",
	    shadeClose: false,
	    shade: 0.3,
	    maxmin: true, //开启最大化最小化按钮
	    area: ["900px", document.body.clientHeight-20+"px"],
	    btn: ["提交并开启流程","保存"],
	    content: "newFormOrder.jsp?title=" + formName+"&relate_id="+relate_id,
	    yes: function(index){ //或者使用btn2
	    	var ifname="layui-layer-iframe"+index//获得layer层的名字
		    var Ifame=window.frames[ifname]//得到框架
		    Ifame.insert(true)
		    return false
	    },btn2: function(index){ //或者使用btn2
		      var ifname="layui-layer-iframe"+index//获得layer层的名字
		      var Ifame=window.frames[ifname]//得到框架
		      Ifame.insert(false)
		      return false
		    }
	  })
  } else {
    layer.open({
	    type: 2,
	    title: "添加数据",
	    shadeClose: false,
	    shade: 0.3,
	    maxmin: true, //开启最大化最小化按钮
	    area: ["900px", document.body.clientHeight-20+"px"],
	    btn: "保存",
	    content: "newFormOrder.jsp?title=" + formName+"&relate_id="+relate_id,
	    yes:function(index){
	    	var ifname="layui-layer-iframe"+index//获得layer层的名字
        var Ifame=window.frames[ifname]//得到框架
        Ifame.insert(false)
        return false
	    }
	  })
  }
}
//新增成功
function addDialogCallBackSuccess1 (index) {
	layer.close(index)
  messageSaveOK()
  $('#dg').datagrid('reload')
}
 function addDialogCallBackSuccess(uuid,params,index){
 	    var str =uuid+","+formUrl+","+tableName;
 		console.info("=str="+str);
 		$.ajax({
	 	        url: "<%=basePath%>/flow/startProcessWithForm",
	 			type : "POST",
	 			dataType : 'json',
	 			data : {
	 				modelName:key,
	 				uuid :uuid ,
	 				variable:params,
	 				completeNow:true
	 			},
	 			success : function(result)//成功
	 			{
	 				layer.msg(result.msg);
	 				var pid=result.obj.rootId;
	 				layer.open({
	 	    		  type: 2,
	 	    		    title: "指定表单别名",
	 	    		    shadeClose: false,
	 	    		    shade: 0.3,
	 	    		    maxmin: true, //开启最大化最小化按钮
	 	    		    area: ["380px","200px"],
	 	    		    btn: ["保存"],
	 	    		    content: "<%=basePath%>/tips/toAddTips",
	 	    		    yes:function(index){
	 	    		    	var res = window["layui-layer-iframe" + index].callbackdata();
	 	    		    	$.ajax({
	 	    	 	 	        url: "<%=basePath%>/tips/addTips",
	 	    	 	 			type : "POST",
	 	    	 	 			dataType : 'json',
	 	    	 	 			data : {
	 	    	 	 				tName:res,
	 	    	 	 				procInsId :pid ,
	 	    	 	 			},
	 	    	 	 			success : function(result)//成功
	 	   	 					{
								layer.msg(result.msg);
	 	   	 					}
	 	   	 				});
	 	    		    	layer.close(index); 
	 	    		    	location.reload();
	 	    		    }
	 	    	  	});
	 			}
	 		});	
 		
  	}

//修改一条数据
function functionModify () {
  var row = $('#dg').datagrid('getSelected')
  if (row == null) {
    alert('请先选择一条数据')
    return false
  }

  var flag = true
  if (isAct == '0') {
    $.ajax({
      url: "<%=basePath%>/flow/getStats",
      type : "POST",
      dataType : 'json',
      async: false,
      data : {
        'uuid': row.uuid
      },
      success : function(result)//成功
      {

        if (result.msg != '未开启'&& result.msg != '项目经理'){
          flag = false
        }
      }
    })
  }
  if (flag) {
    if (isAct == '0') {
      layer.open({
        type: 2,
        title: '修改数据',
        shadeClose: false,
        shade: 0.3,
        maxmin: true, //开启最大化最小化按钮
        area: ['900px', document.body.clientHeight-20+'px'],
        btn: ['提交并开启流程','保存'],
        content: 'editFormOrder.jsp?title=' + formName + '&uuid=' + row.uuid,
        yes: function(index){ //或者使用btn2
          var ifname="layui-layer-iframe"+index//获得layer层的名字
          var Ifame=window.frames[ifname]//得到框架
          Ifame.update(true)
          return false
        },btn2: function(index){ //或者使用btn2
          var ifname="layui-layer-iframe"+index//获得layer层的名字
          var Ifame=window.frames[ifname]//得到框架
          Ifame.update(false)
          return false
        }
      })
    } else {
      layer.open({
        type: 2,
        title: '修改数据',
        shadeClose: false,
        shade: 0.3,
        maxmin: true, //开启最大化最小化按钮
        area: ['900px', document.body.clientHeight-20+'px'],
        btn: '保存',
        content: 'editFormOrder.jsp?title=' + formName + '&uuid=' + row.uuid,
        yes:function(index){
          var ifname="layui-layer-iframe"+index//获得layer层的名字
          var Ifame=window.frames[ifname]//得到框架
          Ifame.update(false)
          return false
        }
      })
    }
  } else {
    $.messager.alert('提醒', '流程已开启，不能修改数据。', 'warning')
  }
}
//传输表单Json
function transferFormJson () {
  return result
}
//传输选中数据
function transferRowData () {
  var row = $('#dg').datagrid('getSelected')
  return row
}
//修改成功
function editDialogCallBackSuccess1 (index) {
	layer.close(index)
  messageSaveOK()
  $('#dg').datagrid('reload')
}
function editDialogCallBackSuccess(uuid){
	    var str =uuid+","+formUrl+","+tableName;
		console.info("=str="+str);
		$.ajax({
 	        url: "<%=basePath%>/flow/startProcessWithForm",
 			type : "POST",
 			dataType : 'json',
 			data : {
 				modelName:key,
 				uuid :uuid ,
 				completeNow:true
 			},
 			success : function(result)//成功
 			{
 				layer.msg(result.msg);
 				var pid=result.obj.rootId;
 				layer.open({
 	    		  type: 2,
 	    		    title: "指定表单别名",
 	    		    shadeClose: false,
 	    		    shade: 0.3,
 	    		    maxmin: true, //开启最大化最小化按钮
 	    		    area: ["380px","200px"],
 	    		    btn: ["保存"],
 	    		    content: "<%=basePath%>/tips/toAddTips",
 	    		    yes:function(index){
 	    		    	var res = window["layui-layer-iframe" + index].callbackdata();
 	    		    	$.ajax({
 	    	 	 	        url: "<%=basePath%>/tips/addTips",
 	    	 	 			type : "POST",
 	    	 	 			dataType : 'json',
 	    	 	 			data : {
 	    	 	 				tName:res,
 	    	 	 				procInsId :pid ,
 	    	 	 			},
 	    	 	 			success : function(result)//成功
 	   	 					{
							layer.msg(result.msg);
 	   	 					}
 	   	 				});
 	    		    	layer.close(index); 
 	    		    	location.reload();
 	    		    }
 	    	  	});
 			}
 		});	
	}
//查看一条数据
function functionView () {
  var row = $('#dg').datagrid('getSelected')
  if (row == null) {
    alert('请先选择一条数据')
    return false
  }
  layer.open({
    type: 2,
    title: '查看数据',
    shadeClose: false,
    shade: 0.3,
    maxmin: true, //开启最大化最小化按钮
    area: ['900px', document.body.clientHeight-20+'px'],
    btn: '关闭',
    content: 'seeFormOrder.jsp?title=' + formName + '&uuid=' + row.uuid,
    yes:function(index){
      layer.close(index)
    }
  })
}
//删除一条数据
function functionDelete () {
  var row = $('#dg').datagrid('getSelected')
  if(row == null) {
    alert('请先选择一条数据')
    return false
  } else {
    var flag = true
    if (isAct == '0') {
      $.ajax({
        url: "<%=basePath%>/flow/getStats",
        type : "POST",
        dataType : 'json',
        async: false,
        data : {
          'uuid': row.uuid
        },
        success : function(result)//成功
        {
          if (result.msg != '未开启'&& result.msg != '项目经理'){
            flag = false
          }
        }
      })
    }
    if (flag) {
      $.messager.confirm('确认','您确认想要删除吗？',function(r){
        if (r){
          $.ajax({
            url: "<%=basePath%>/crm/ActionFormUtil/delete.do",
            type: "POST",
            dataType:'text',
            data:
            {
              'tableName': formName,
              'id': row.id
            },
            error: function() //失败
            {
              messageDeleteError()
            },
            success: function(data)//成功
            {
              data = $.trim(data)
              if(data == '0'){
                messageDeleteError()
              }else{
                messageDeleteOK()
              $('#dg').datagrid('reload')
              }
            }
          })
        }
      })
    } else {
      $.messager.alert('提醒', '流程已开启，不能删除数据。', 'warning')
    }
  }
}
// 生成图表
function setCharts () {
  layer.open({
    type: 2,
    title: '生成图表',
    shadeClose: false,
    shade: 0.3,
    maxmin: true, //开启最大化最小化按钮
    area: ['900px', document.body.clientHeight-20+'px'],
    btn: '关闭',
    content: '<%=basePath%>/pages/charts/charts.jsp?formName=' + formName,
    yes:function(index){
      layer.close(index)
    }
  })
}
// 搜索
function search1 () {
  var searchs = eval(formFramework.searchs)
  var conditions = ''
  for (var i = 0; i < searchs.length; i++) {
    var valueTemp = ''
    if (searchs[i].searchType == 'textbox') {
      valueTemp = $('#'+searchs[i].searchId).textbox('getValue')
    } else if (searchs[i].searchType == 'combobox') {
      valueTemp = $('#'+searchs[i].searchId).combobox('getValue')
    } else if (searchs[i].searchType == 'datebox') {
      valueTemp = $('#'+searchs[i].searchId).datebox('getValue')
    }
    if (!checkNull(valueTemp)) {
      if (searchs[i].searchCondition == 'equal') {
        conditions += " and "+searchs[i].searchField+" = '"+valueTemp+"'"
      } else if (searchs[i].searchCondition == 'notEqual') {
        conditions += " and "+searchs[i].searchField+" <> '"+valueTemp+"'"
      } else if (searchs[i].searchCondition == 'contains') {
        conditions += " and "+searchs[i].searchField+" like '%"+valueTemp+"%'"
      } else if (searchs[i].searchCondition == 'notContains') {
        conditions += " and "+searchs[i].searchField+" not like '%"+valueTemp+"%'"
      } else if (searchs[i].searchCondition == 'isEmpty') {
        conditions += " and "+searchs[i].searchField+" "+valueTemp+""
      } else if (searchs[i].searchCondition == 'greater') {
        conditions += " and "+searchs[i].searchField+" > '"+valueTemp+"'"
      } else if (searchs[i].searchCondition == 'less') {
        conditions += " and "+searchs[i].searchField+" < '"+valueTemp+"'"
      }
      // conditions.push({
      //   'field': searchs[i].searchField,
      //   'value': valueTemp,
      //   'condition': searchs[i].searchCondition
      // })
    }
  }
  if (result.needTree=='true') {
    var relate_id = ''
    var treeRow = $('#dg_tree').treegrid('getSelected')
    if (treeRow == null) {
      alert('请先选择一条数据')
      return false
    } else {
      relate_id = treeRow.id
      $('#dg').datagrid({
        url: "<%=basePath%>/crm/ActionFormUtil/getByTableNameAndSearchAndPid.do?tableName="+formName+"&create_user_id="+user.id,
        columns:columns,
        queryParams:{
          conditions:conditions,
          pid:relate_id
        },
        rownumbers:true,
        singleSelect:true,
        autoRowHeight:false,
        pagination:true,
        fitColumns:true,
        striped:true,
        toolbar:'#tb',
        pageSize:20
      })
    }
  } else {
    $('#dg').datagrid({
      url: "<%=basePath%>/crm/ActionFormUtil/getByTableNameAndSearch.do?tableName="+formName+"&create_user_id="+user.id,
      columns:columns,
      queryParams:{
        conditions:conditions
      },
      rownumbers:true,
      singleSelect:true,
      autoRowHeight:false,
      pagination:true,
      fitColumns:true,
      striped:true,
      toolbar:'#tb',
      pageSize:20
    })
  }
}
</script>
